package com.cly.common.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.cly.common.exception.AuthCodeException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthCodeUtil {
    private static final String ACCESS_KEY_ID="LTAI5tRpNzdudadBUwYcJRhC";
    private static final String ACCESS_KEY_SECRET="2oFVypBs2y4j2IBck8GQ9eCwykQzQ3";

    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    /**
     * 发送验证码
     * @param phone 目标手机号
     * @param code  验证码
     * @throws Exception
     */
    public static void sendCode(String phone, String code) throws Exception {
        // 设置Dysmsapi客户端参数
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        config.endpoint = ENDPOINT;
        // 创建客户端
        Client client = new Client(config);
        //构造请求对象，填入请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone) //  手机号
                .setSignName("")        // 签名名称
                .setTemplateCode("")    //  模板名称
                .setTemplateParam("{\"code\":\"" + code + "\"}");// 需要发送的内容
        // 发送短信,接收响应
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        // 处理响应
        if ("OK".equals(sendSmsResponse.getBody().getCode())) {
            log.info("短信发送成功");
        } else {
            // 处理失败情况
            log.info("短信发送失败:{}", sendSmsResponse.getBody().getMessage());
            throw new AuthCodeException("短信发送失败");
        }
    }
}
